package it.ma.musicplayernew.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.zhongdao.swing.R;

import java.util.List;

import it.ma.musicplayernew.MainActivity;
import it.ma.musicplayernew.helper.ImageLoaderHelper;
import it.ma.musicplayernew.loaders.TrackListAdapter;
import it.ma.musicplayernew.modle.Track;
import it.ma.musicplayernew.service.CoreService;
import it.ma.musicplayernew.utils.MediaUtils;

public class AllTracks extends Base {

    public static final String SERVICECMD = "com.android.music.musicservicecommand";
    public static final String CMDNAME = "command";
    public static final String CMDTOGGLEPAUSE = "togglepause";
    public static final String CMDSTOP = "stop";
    public static final String CMDPAUSE = "pause";
    public static final String CMDPREVIOUS = "previous";
    public static final String CMDNEXT = "next";
    public static final String TOGGLEPAUSE_ACTION = "com.android.music.musicservicecommand.togglepause";
    public static final String PAUSE_ACTION = "com.android.music.musicservicecommand.pause";
    public static final String PREVIOUS_ACTION = "com.android.music.musicservicecommand.previous";
    public static final String NEXT_ACTION = "com.android.music.musicservicecommand.next";

    private View mRootView;
    @ViewInject(R.id.listView1)
    private ListView mListView;
    // control buttons
    @ViewInject(R.id.btn_play_local)
    private ImageButton mPlayButton;
    @ViewInject(R.id.btn_next_local)
    private ImageButton mNextButton;
    @ViewInject(R.id.btn_pre_local)
    private ImageButton mPreviousButton;
    @ViewInject(R.id.title)
    private TextView titleTextView;
    @ViewInject(R.id.iv_art_bottom)
    private ImageView mArtImageView;
    @ViewInject(R.id.iv_bg)
    private ImageView mIvBg;

	private TrackListAdapter mAdapter;

	private MainActivity mActivity;
	private CoreService mServiceCallback;
    private Animation mAnimationFade;

    private long mSongId;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_all, null);

        ViewUtils.inject(this, mRootView);

        registerMusicReceiver();

        initAnim();

		return mRootView;
	}

    private void initAnim() {
        mAnimationFade = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_in);
    }

    private void registerMusicReceiver() {
        IntentFilter commandFilter = new IntentFilter();
        commandFilter.addAction(SERVICECMD);
        commandFilter.addAction(TOGGLEPAUSE_ACTION);
        commandFilter.addAction(PAUSE_ACTION);
        commandFilter.addAction(NEXT_ACTION);
        commandFilter.addAction(PREVIOUS_ACTION);
        commandFilter.setPriority(Integer.MAX_VALUE);
        getActivity().registerReceiver(mIntentReceiver, commandFilter);
    }

    private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            String cmd = intent.getStringExtra("command");
            Log.d("AllTracks", "action : " + action + " cmd : " + cmd);
            if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
                next(null);
            } else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
                previous(null);
            } else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
                play(null);
            } else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
                mServiceCallback.pausePlayer();
            } else if (CMDSTOP.equals(cmd)) {
                mServiceCallback.pausePlayer();
            }
            abortBroadcast();
        }
    };

    @Override
	public void onAttach(Activity activity) {
		mActivity = (MainActivity) activity;
		super.onAttach(activity);
	}

    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(mIntentReceiver);
        super.onDestroy();
    }

    public void setServiceCallback(CoreService serviceCallback){
        mServiceCallback = serviceCallback;
        Log.i("nick", mServiceCallback.toString());

        display();
    }

    /**
     * 更新背景
     *
     * @param drawable
     */
    public void onBlurReady(Drawable drawable) {

        if (drawable != null && mServiceCallback != null && mServiceCallback.getCurrentSongId() != mSongId) {
            mIvBg.setImageDrawable(drawable);
            mIvBg.startAnimation(mAnimationFade);
            mSongId = mServiceCallback.getCurrentSongId();
        }
    }

	@Override
	public void onStart() {
		super.onStart();
	}

    @OnClick(R.id.btn_play_local)
    public void play(View view){
        if(mServiceCallback == null){
            return;
        }
        if(view != null){
            //按钮被点击
            mActivity.mMainFragment.updatePlayMode(ControlPanelFragment2.MOBILE_MODE);
        }else{
            //广播调用
            mActivity.mMainFragment.updateModeDisplay(ControlPanelFragment2.MOBILE_MODE);
        }

        if (mServiceCallback.getIsPlaying()) {
            mServiceCallback.pausePlayer();
        } else {
            mServiceCallback.resumePlayer();
        }
    }

    @OnClick(R.id.btn_pre_local)
    public void previous(View view){
        if(mServiceCallback == null){
            return;
        }

        if(view != null){
            //按钮被点击
            mActivity.mMainFragment.updatePlayMode(ControlPanelFragment2.MOBILE_MODE);
        }else{
            //广播调用
            mActivity.mMainFragment.updateModeDisplay(ControlPanelFragment2.MOBILE_MODE);
        }

        mServiceCallback.playPreviousTrack();
    }

    @OnClick(R.id.btn_next_local)
    public void next(View view){
        if(mServiceCallback == null){
            return;
        }

        if(view != null){
            //按钮被点击
            mActivity.mMainFragment.updatePlayMode(ControlPanelFragment2.MOBILE_MODE);
        }else{
            //广播调用
            mActivity.mMainFragment.updateModeDisplay(ControlPanelFragment2.MOBILE_MODE);
        }

        mServiceCallback.playNextTrack();
    }

    /**
     * 显示歌曲
     */
	void display() {
		new TrackLoaderTask().execute();
	}

	/**
	 * @return
	 */
	List<Track> getTracks() {
		return MediaUtils.getTrackList(getActivity());
	}

	/**
     * 填充listView
	 * @param tracks
	 */
	void inflateListView(final List<Track> tracks) {

        if(mAdapter == null){
            mAdapter = new TrackListAdapter(tracks, getActivity());
        }else{
            mAdapter.setTracks(tracks);
            mAdapter.notifyDataSetChanged();
        }
		mListView.setAdapter(mAdapter);

		mServiceCallback.setupPLayList(tracks);

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {


                if (mServiceCallback.getPlayList() != tracks) {
                    mServiceCallback.setupPLayList(tracks);
                }
                mServiceCallback.setCurrentCursor(position);
                mServiceCallback.playTrack(position);

                mActivity.mMainFragment.updatePlayMode(ControlPanelFragment2.MOBILE_MODE);
            }
		});
	}

    /**
     * 异步获取系统歌曲 任务栈
     */
	final class TrackLoaderTask extends AsyncTask<Void, Void, List<Track>> {

		@Override
		protected List<Track> doInBackground(Void... arg0) {
			return getTracks();
		}

		@Override
		protected void onPostExecute(List<Track> result) {
			inflateListView(result);
			super.onPostExecute(result);
		}
	}

	@Override
	public void onPraisedPressed() {
		
	}

    public void onPlayUpdate(Track track){
        if(track == null) return;
        updateControlButtonBackground();
        updateArtImage(MediaUtils.parseAlbumUrl(String.valueOf(track.getAlbumId())).toString());
        updateTitle(track.getTitle());

        if(mAdapter == null){
            mAdapter = new TrackListAdapter(getActivity());
        }
        mAdapter.setCurrTackId(track.getId());
        mAdapter.notifyDataSetChanged();

    }

    /**
     * 更新播放按钮显示
     */
    public void updateControlButtonBackground() {
        try {
            if (mServiceCallback != null && mServiceCallback.getIsPlaying()) {
                mPlayButton.setImageResource(R.mipmap.notification_pause);
            } else {
                mPlayButton.setImageResource(R.mipmap.notification_play);
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    /**
     * 更新头像
     */
    public void updateArtImage(String albumUri) {
        ImageLoaderHelper.displayImage(albumUri,mArtImageView,R.mipmap.default_artist);
    }

    /**
     * 更新歌名
     * @param title
     */
    public void updateTitle(String title) {
        titleTextView.setText(title);
    }

}
